package com.yingjia.yingjiauniversity.http.presenter;

import com.trello.rxlifecycle2.LifecycleTransformer;
import com.yingjia.yingjiauniversity.base.BaseEntry;
import com.yingjia.yingjiauniversity.base.BasePresenter;
import com.yingjia.yingjiauniversity.bean.base.SignatureEntity;
import com.yingjia.yingjiauniversity.bean.http.ObtainSignature;
import com.yingjia.yingjiauniversity.http.HttpObserver;
import com.yingjia.yingjiauniversity.http.datasource.SignatureRemoteDataSourceImpl;
import com.yingjia.yingjiauniversity.http.datasource.SignatureRepository;
import com.yingjia.yingjiauniversity.http.exception.ApiServerResultFunction;
import com.yingjia.yingjiauniversity.http.exception.BaseException;
import com.yingjia.yingjiauniversity.http.iinterface.SignatureInfoMvpPresenter;
import com.yingjia.yingjiauniversity.http.iinterface.SignatureInfoMvpView;
import com.yingjia.yingjiauniversity.utils.AppToast;

import io.reactivex.disposables.CompositeDisposable;

/**
 * Created by mars.yu on 2017/11/20.
 *
 * @param <V> the type parameter
 */
public class SignatureInfoPresenter<V extends SignatureInfoMvpView> extends BasePresenter<V> implements
        SignatureInfoMvpPresenter<V> {
    private SignatureRepository signatureRepository;

    private CompositeDisposable compositeDisposable;

    /**
     * Instantiates a new Main presenter.
     */
    public SignatureInfoPresenter(CompositeDisposable compositeDisposable) {
        signatureRepository = SignatureRepository.getInstance(new SignatureRemoteDataSourceImpl());
        this.compositeDisposable = compositeDisposable;
    }

    @Override
    public void getSignatureInfo(String orderNo,
                                 LifecycleTransformer<SignatureEntity<ObtainSignature>> lifecycleTransformer) {

        signatureRepository.getSignatureInfo(orderNo).map(new ApiServerResultFunction<ObtainSignature>())
                .compose(lifecycleTransformer).subscribe(new HttpObserver<ObtainSignature>(compositeDisposable) {

            @Override
            public void onError(BaseException e) {
                AppToast.show(e.getMsg());
                getMvpView().showSignatureInfoFail(e);
            }

            @Override
            public void onSucess(BaseEntry<ObtainSignature> response) {
                if (response.getResultData() != null) {
                    getMvpView().showSignatureInfo(response.getResultData());
                } else {
                    getMvpView().showSignatureInfo(null);
                }
            }
        });
    }

}
